package com.zqxq.lottery.service.product.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.lottery.common.utils.ExcelUtils;
import com.zqxq.lottery.entity.bo.product.ProductBO;
import com.zqxq.lottery.entity.bo.product.ProductSearchBO;
import com.zqxq.lottery.entity.o2o.product.ProductO2O;
import com.zqxq.lottery.entity.po.product.ProductPO;
import com.zqxq.lottery.entity.po.sys.SysConfigPO;
import com.zqxq.lottery.entity.vo.product.ProductVO;
import com.zqxq.lottery.entity.vo.user.UserInfoVO;
import com.zqxq.lottery.mapper.product.ProductMapper;
import com.zqxq.lottery.mapper.sys.SysConfigMapper;
import com.zqxq.lottery.service.product.IProductService;
import com.zqxq.lottery.service.user.IUserAddressService;
import com.zqxq.lottery.service.user.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> implements IProductService {
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserAddressService userAddressService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Override
    public ProductVO save(ProductVO vo) throws Exception {
        ProductPO po = ProductO2O.toPO(vo);
        if (vo.getId()==null) {
            baseMapper.insert(po);
        } else {
            baseMapper.updateById(po);
        }
        return vo;
    }
    @Override
    public Page queryPage(ProductBO search) throws Exception {
        Page page = new Page(search.getPageNo(), search.getPageSize());
        List<ProductVO> list = baseMapper.queryPage(page, search);
        page.setRecords(list);
        return page;
    }
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public boolean excelBatchInsert(String fileName, MultipartFile file,boolean isUpdate) throws Exception {
        boolean notNull = false;
        List<ProductPO> productPOList = new ArrayList<ProductPO>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        ProductPO productPO;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            productPO = new ProductPO();
            int count = 0;
            String prductId = "";
            if(isUpdate){
                count = 1;
                prductId = row.getCell(0).getStringCellValue();
                if(prductId == null || prductId.isEmpty()){
                    throw new Exception("导入失败(第"+(r+1)+"行,产品编号未填写)");
                }
            }
            String calss = row.getCell(count+0).getStringCellValue();
            if(calss == null || calss.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品种类未填写)");
            }
            String type = row.getCell(count+1).getStringCellValue();
            if(type == null || type.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品分类未填写)");
            }
            String detailType = row.getCell(count+2).getStringCellValue();
            if(detailType==null || detailType.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品二级分类未填写)");
            }
            String model = row.getCell(count+3).getStringCellValue();
            if(model==null || model.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品型号未填写)");
            }
            String color = row.getCell(count+4).getStringCellValue();
            if(color==null || color.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品颜色未填写)");
            }
            String version = row.getCell(count+5).getStringCellValue();
            if(version==null || version.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品版本未填写)");
            }
            String price = ExcelUtils.getCellValue(row.getCell(count + 6));
            if (price == null || price.isEmpty()) {
                throw new Exception("导入失败(第" + (r + count + 1) + "行,产品价格未填写)");
            }
            String exchangeRate = ExcelUtils.getCellValue(row.getCell(count+7));
            if(exchangeRate==null || exchangeRate.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品兑换量未填写)");
            }
            String sort = ExcelUtils.getCellValue(row.getCell(count+8));
            if(sort==null || sort.isEmpty()){
                throw new Exception("导入失败(第"+(r+count+1)+"行,产品排序未填写)");
            }
            productPO.setPrice(new BigDecimal(price));
            productPO.setExchange_rate(new BigDecimal(exchangeRate));
            productPO.setSort(Integer.valueOf(sort));
            if(isUpdate){
                productPO.setId(Long.valueOf(prductId));
            }
            Integer productCalss = calss.equals("实体商品")?0:1;
            productPO.setCalss(productCalss);
            productPO.setType(type);
            productPO.setDetail_type(detailType);
            productPO.setModel(model);
            productPO.setColor(color);
            productPO.setVersion(version);
            productPOList.add(productPO);
        }
        for (ProductPO product : productPOList) {
            if(isUpdate){
                baseMapper.updateById(product);
            }else {
                baseMapper.insert(product);
            }
        }
        return notNull;
    }
    @Override
    public List<ProductVO> query(ProductSearchBO search) throws Exception {
        return baseMapper.queryPage(search);
    }

    @Override
    public Map<String,Object> payDataProcure(Long userId, Long productId) throws Exception {
        UserInfoVO userInfoVO = userInfoService.getVO(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo",userInfoVO);
        ProductPO po = baseMapper.selectById(productId);
        map.put("productInfo",ProductO2O.toVO(po));
        map.put("addressInfo",userAddressService.selectById(userInfoVO.getAddressId()));
        SysConfigPO config1 = sysConfigMapper.getByKey("PRODUCT_DISCOUNT_RATE");
        String value1 = config1.getCval();
        SysConfigPO config2 = sysConfigMapper.getByKey("SELL_FOR_SALE_EXPLAIN");
        String value2 = config2.getCval();
        SysConfigPO config3 = sysConfigMapper.getByKey("EXCHANGE_MONEY_FOR_SALE_SWITCH");
        String value3 = config3.getCval();
        map.put("productDiscountRate",value1);
        map.put("sellForSaleExplain",value2);
        map.put("exchangeMoneyForSaleSwitch",value3);
        return map;
    }
}
